package com.xiaoxu.privatechat.controller.common;

import com.xiaoxu.privatechat.bean.CodeMsg;
import com.xiaoxu.privatechat.bean.Result;
import com.xiaoxu.privatechat.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @author xiaoxu
 * @description 公用的上传类
 * @date 2023/2/13
 */
@RequestMapping("/upload")
@Controller
public class UploadController {

    /**
     * 上传图片后缀
     */
    @Value("${ylrc.upload.photo.suffix}")
    private String uploadPhotoSuffix;

    /**
     * 上传图片最大大小
     */
    @Value("${ylrc.upload.photo.maxsize}")
    private long uploadPhotoMaxSize;

    /**
     * 图片保存位置
     */
    @Value("${ylrc.upload.photo.path}")
    private String uploadPhotoPath;

    /**
     * 文件上传最大大小
     */
    @Value("${ylrc.upload.file.maxsize}")
    private long uploadFileMaxSize;

    /**
     * 文件保存位置
     */
    @Value("${ylrc.upload.file.path}")
    private String uploadFilePath;

    private final Logger log = LoggerFactory.getLogger(UploadController.class);

    /**
     * @param photo 图片文件
     * @return Result
     * @description 图片统一上传类
     */
    @RequestMapping(value = "/upload_photo", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> uploadPhoto(@RequestParam(name = "photo") MultipartFile photo) {
        //判断文件类型是否是图片
        String originalFilename = photo.getOriginalFilename();
        //获取文件后缀
        String suffix = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf("."), originalFilename.length());
        if (!uploadPhotoSuffix.contains(suffix.toLowerCase())) {
            return Result.error(CodeMsg.UPLOAD_PHOTO_SUFFIX_ERROR);
        }
        if (photo.getSize() / 1024 > uploadPhotoMaxSize) {
            CodeMsg codeMsg = CodeMsg.UPLOAD_PHOTO_ERROR;
            codeMsg.setMsg("圖片大小不能超過" + (uploadPhotoMaxSize / 1024) + "M");
            return Result.error(codeMsg);
        }
        //准备保存文件
        String filename = null;
        try {
            File filePath = new File(uploadPhotoPath);
            if (!filePath.exists()) {
                //若不存在文件夹，则创建一个文件夹
                boolean Bool = filePath.mkdir();
                if (!Bool) {
                    throw new IOException("資料夾創建失敗");
                }
            }
            filePath = new File(uploadPhotoPath + "/" + StringUtil.getFormatterDate(new Date(), "yyyyMMdd"));
            //判断当天日期的文件夹是否存在，若不存在，则创建
            if (!filePath.exists()) {
                //若不存在文件夹，则创建一个文件夹
                boolean Bool = filePath.mkdir();
                if (!Bool) {
                    throw new IOException("資料夾創建失敗");
                }
            }
            filename = StringUtil.getFormatterDate(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + suffix;
            photo.transferTo(new File(uploadPhotoPath + "/" + filename));
        } catch (IllegalStateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        log.info("圖片上傳成功，保存位置：" + uploadPhotoPath + filename);
        return Result.success(filename);
    }

    /**
     * @param file 文件
     * @return Result
     * @description 文件统一上传类
     */
    @RequestMapping(value = "/upload_file", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> uploadFile(@RequestParam(name = "file") MultipartFile file) {
        //判断文件类型是否是图片
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf("."), originalFilename.length());
        if (file.getSize() / 1024 > uploadFileMaxSize) {
            CodeMsg codeMsg = CodeMsg.UPLOAD_PHOTO_ERROR;
            codeMsg.setMsg("文件大小不能超過" + (uploadFileMaxSize / 1024) + "M");
            return Result.error(codeMsg);
        }
        //准备保存文件
        String filename = null;
        try {
            File filePath = new File(uploadFilePath);
            if (!filePath.exists()) {
                //若不存在文件夹，则创建一个文件夹
                boolean Bool = filePath.mkdir();
                if (!Bool) {
                    throw new IOException("資料夾創建失敗");
                }
            }
            filePath = new File(uploadFilePath + "/" + StringUtil.getFormatterDate(new Date(), "yyyyMMdd"));
            //判断当天日期的文件夹是否存在，若不存在，则创建
            if (!filePath.exists()) {
                //若不存在文件夹，则创建一个文件夹
                filePath.mkdir();
            }
            filename = StringUtil.getFormatterDate(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + suffix;

            file.transferTo(new File(uploadFilePath + "/" + filename));
        } catch (IllegalStateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        log.info("文件上傳成功，保存位置：" + uploadFilePath + filename);
        return Result.success(filename);
    }

}
